package com.cbs.android.module.discussion.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import com.cbs.android.component.application.activity.CBSActivity;
import com.cbs.android.component.application.activity.delayedtask.DelayedTask;
import com.cbs.android.component.application.activity.handler.CBSSimpleActivityResultHandler;
import com.cbs.android.component.applicationutils.Global;
import com.cbs.android.component.applicationutils.network.ErrorResponse;
import com.cbs.android.component.network.HttpClient;
import com.cbs.android.component.network.Request;
import com.cbs.android.component.network.SimpleResponseHandler;
import com.cbs.android.component.sensitivewords.SensitiveWords;
import com.cbs.android.component.toast.Toast;
import com.cbs.android.module.discussion.DiscussionModule;
import com.cbs.android.module.discussion.R;
import com.cbs.android.module.discussion.entity.CommentSnapshot;
import com.cbs.android.module.discussion.utils.Constants;
import com.cbs.android.module.discussion.utils.DiscussionActivityType;
import com.cbs.android.module.discussion.utils.SimpleJsonCombiner;
import com.cbs.android.module.user.network.CBSUserRequest;
import com.cbs.android.module.user.user.UserModule;
import com.cbs.android.module.userkit.UserKit;
import com.google.gson.Gson;

import org.apache.commons.lang3.StringUtils;

import okhttp3.FormBody;
import okhttp3.RequestBody;

/**
 * Created by broche on 10/24/15.
 */
public class CommentAddActivity extends CBSActivity {
    private static final String TAG = CommentAddActivity.class.getName();
    private static final String CommentsUrlTpl = "social/api/v1/forums/%d/subjects/%d/comments";
    private int forumId = -1;
    private int subjectId = -1;
    private CommentSnapshot commentSnapshot;
    private String subjectSnapshotStr;
    private HttpClient httpClient = Global.getHttpClient().clone();
    private EditText contentView;
    private View submitView;

    @Override
    protected int getDefaultFinishInAnim() {
        return 0;
    }

    @Override
    protected int getDefaultFinishOutAnim() {
        return R.anim.cbs_slide_out_bottom;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.cbs_discussion_commentadd);

        setResult(RESULT_CANCELED);
        httpClient.setDebug(DiscussionModule.isDebug());

        forumId = getIntent().getIntExtra(Constants.ForumId, -1);
        subjectId = getIntent().getIntExtra(Constants.SubjectId, -1);
        commentSnapshot = new Gson().fromJson(getIntent().getStringExtra(Constants.CommentSnapshot), CommentSnapshot.class);
        subjectSnapshotStr = getIntent().getStringExtra(Constants.SubjectSnapshot);

        if (forumId < 0) {
            Toast.show(getString(R.string.cbs_discussion_hint_paramerror));
            finish();
            return;
        }
        if (subjectId < 0) {
            Toast.show(getString(R.string.cbs_discussion_hint_paramerror));
            finish();
            return;
        }
        if (StringUtils.isEmpty(subjectSnapshotStr)) {
            Toast.show(getString(R.string.cbs_discussion_hint_paramerror));
            finish();
            return;
        }

        findViewById(R.id.cbs_discussion_commentadd_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        findViewById(R.id.cbs_discussion_commentadd_background).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        findViewById(R.id.cbs_discussion_commentadd_panel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            }
        });
        contentView = (EditText) findViewById(R.id.cbs_discussion_commentadd_content);
        submitView = findViewById(R.id.cbs_discussion_commentadd_submit);
        submitView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (UserModule.getUser() == null) {
                    UserKit.login(CommentAddActivity.this, new CBSSimpleActivityResultHandler() {
                        @Override
                        public void onSuccess(int i, Intent intent) {
                            Toast.show(getString(R.string.cbs_discussion_hint_loginsuccess));
                        }

                        @Override
                        public void onCancel(int i, Intent intent) {
                            Toast.show(getString(R.string.cbs_discussion_hint_logincanceled));
                        }
                    });
                    return;
                }
                String content = contentView.getText().toString();
                if (isEmpty(content)) {
                    Toast.show(getString(R.string.cbs_discussion_verify_emptycontent));
                    return;
                }
                String word;
                if ((word = SensitiveWords.verify(content)) != null) {
                    Toast.show(String.format(getString(R.string.cbs_discussion_verify_sensitivewords), word));
                    return;
                }

                submitView.setEnabled(false);
                commentSnapshot.setContent(content);
                String commentSnapshotStr = new Gson().toJson(commentSnapshot);
                String snapshot = SimpleJsonCombiner.combineObject(subjectSnapshotStr, commentSnapshotStr);
                RequestBody requestBody = new FormBody.Builder()
                        .add("content", content)
                        .add("type", forumId + "_" + DiscussionActivityType.Comment)
                        .add("snapshot", snapshot)
                        .build();
                Request request = new CBSUserRequest(String.format(Global.getServerHost() + "/" + CommentsUrlTpl, forumId, subjectId))
                        .post(requestBody)
                        .setResponseHandler(new SimpleResponseHandler() {
                            @Override
                            public void onSuccess(Object entity) {
                                submitView.setEnabled(true);
                                Toast.show(getString(R.string.cbs_discussion_hint_sendsuccess));
                                setResult(RESULT_OK);
                                finish();
                            }

                            @Override
                            public void onFailure(int code, String message) {
                                submitView.setEnabled(true);
                                ErrorResponse errorResponse = new Gson().fromJson(message, ErrorResponse.class);
                                Toast.show(errorResponse.getErrorMsg());
                            }

                            @Override
                            public void onException(Request request, Exception e) {
                                super.onException(request, e);
                                submitView.setEnabled(true);
                            }
                        });
                httpClient.send(request);
            }
        });

        doDelayed(new DelayedTask() {
            @Override
            public void doDelayed(Bundle data) {
                contentView.requestFocus();
                ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).showSoftInput(contentView, 0);
            }
        }, 1000);
    }

    private boolean isEmpty(String entry) {
        if (entry == null) {
            return true;
        }
        for (int i = 0; i < entry.length(); i++) {
            String s = entry.substring(i, i + 1);
            if (!s.equals(" ") && !s.equals("\n")) {
                return false;
            }
        }
        return true;
    }
}
